import getPhotos
import getDirectory
from Logging_Model import *
from os import getcwd
from re import findall
# from threading import Thread
from multiprocessing import Process


def photo(_list_url):
    logger.info('多进程')
    for u in _list_url:
        try:
            c = getPhotos.main(u)
            if c is 'getHtmlError': logger.error('getPhotos.py: Get Html Error')
            elif c is 'ListPhoto Error': logging.error('getPhotos.py: The HTML in URL has not photos.')
        except:
            Traceback()
            logger.error('getPhotos.py 未正常返回')
    return


def main(_url):
    try:
        urlList = getDirectory.main(_url)
        LUrlList = urlList[0::4], urlList[1::4], urlList[2::4], urlList[3::4]
        global p
        for LU in LUrlList:
            p = Process(target=photo, args=(LU,))
            p.start()
        p.join()
    except TimeoutError:
        Traceback()
        print('*********超时了**********')
    except:
        print('****出错了****')


def Model_page(_url):
    try:
        for i in range(0, 100):
            if _url[i:i+4] == 'page': return 'ok'
    except: pass


def Model():
    while True:
        _model = input('输入模式URL：')
        if not _model[:5] == 'http:': print('输入错误：必须以http:开头')
        elif len(_model) < 20: print('输入错误：URL至少多于20个字符')
        elif Model_page(_model) is not 'ok': print('输入错误：URL中必须有page参数')
        else: return _model


if __name__ == '__main__':
    logger.info(f'*****{Data()}  {Time()}   {getcwd()}*****')
    """ 构造多的DIR URL """
    model = Model()
    # if model is 'Error': model = f'http://w2.xggfgczh781.pw/pw/thread-htm-fid-106-page-1.html'

    model = model.split('page-')
    n = 0
    while True:
        n += 1
        url = model[0] + 'page-' + f'{n}' + findall(r'^\d+(.*)', model[1])[0]
        logger.info(f'*****{url}*****')
        main(url)
